#pragma once
#include <iostream>
#include <queue>
#include <unistd.h>
#include <pthread.h>

const int defaultcap = 5;

template <class T>
class BlockQueue{
private:
    bool isFull() { return _q.size() >= _cap; }
    bool isEmpty() { return _q.empty(); }

public:
    BlockQueue(int cap = defaultcap)
        :_cap(cap), _psleep_num(0), _csleep_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_full_cond, nullptr);
        pthread_cond_init(&_empty_cond, nullptr);
    }

    void Equeue(const T& in)
    {
        pthread_mutex_lock(&_mutex);

        while(isFull())
        {
            _psleep_num++;
            pthread_cond_wait(&_full_cond, &_mutex);
            std::cout << "生产者进入休眠_psleep_num:" << _psleep_num << std::endl;
            _psleep_num--;
        }

        if(_csleep_num > 0)
        {
            pthread_cond_signal(&_empty_cond);
            std::cout << "唤醒一个消费者" << std::endl;
            _csleep_num--;
        }

        _q.push(in);

        pthread_mutex_unlock(&_mutex);

    }

    T Pop()
    {
        pthread_mutex_lock(&_mutex);

        while(isEmpty())
        {
            _csleep_num++;
            pthread_cond_wait(&_empty_cond, &_mutex);
            std::cout << "消费者进入休眠_csleep_num:" << _csleep_num << std::endl;
            _csleep_num--;
        }

        if(_psleep_num > 0)
        {
            pthread_cond_signal(&_full_cond);
            std::cout << "唤醒一个生产者" << std::endl;
        }

        T data = _q.front();
        _q.pop();

        pthread_mutex_unlock(&_mutex);

        return data;
    }

    std::queue<T>& GetQueue()
    {
        return _q;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_full_cond);
        pthread_cond_destroy(&_empty_cond);
    }
private:
    int _cap;
    std::queue<T> _q;

    int _csleep_num;
    int _psleep_num;

    pthread_mutex_t _mutex;
    pthread_cond_t _full_cond;
    pthread_cond_t _empty_cond;

};